const { needParam, N, upperFirst } = require("../../../utils");

module.exports = {
  /**
   * 判断是否是js变量
   * @param {string} name 变量名称
   * @param {boolean} isBlur 是否模糊匹配
   * @returns {boolean} 是否是js变量
   */
  isJsVar(name = needParam(), isBlur = false) {
    const vars = ["exports", "module", "const", "let", "var", "function"];
    if (isBlur) return !!vars.find(it => name.startsWith(it));
    return vars.includes(name);
  },
  /**
   * 将json 转为文件字符串
   * @param {object[]} fields 要处理的fields数据
   * @returns
   */
  letDataToJsFile(data = needParam(), preStr = "") {
    let str = JSON.stringify(data, null, 2);
    if (!preStr) return str;
    preStr = preStr.trim();
    if (!module.exports.isJsVar(preStr, true)) throw new Error(`preStr参数不合法：${preStr}`);
    // JSON.stringify第三个参数2，意为使用2个空格进行缩进
    return `${preStr} ${str}`;
  },
  /**
   * 获取props字符串
   * @param withProps 是否返回props字符串
   * @returns {string}
   */
  getPropsStr(withProps) {
    if (!withProps) return "";
    return `
const props = withDefaults(
  defineProps<{
    _exampleProp?: CommonObj;
  }>(),
  {
    _exampleProp: () => ({}),
  }
);${N}${N}`;
  },
  /**
   * 获取modelData的字符串
   * @param {object} defVal 默认值
   * @returns {string}
   */
  getDefaultModelDataStr(defVal) {
    if (!defVal) return N;
    return `const modelData = reactive(${module.exports.letDataToJsFile(defVal)});`;
  },
  /**
   * 获取插槽的html字符串
   * @param {object[]} fields 要处理的字段
   * @returns {string}
   */
  getSlotHtmlStr(fields = []) {
    const slotFields = fields.filter(it => it.type === "slot");
    let str = "";
    slotFields.forEach((it, i) => {
      const { prop } = it;
      const isLast = i === slotFields.length - 1;
      str += `<template #${prop}>${prop}</template>${isLast ? "" : N}`;
    });
    return str;
  },
  /**
   * 获取按钮字符串
   * @param {object[]} btns 要处理的按钮
   * @param {extraBtns|operateBtns} type 按钮类型
   * @returns
   */
  getBtnsStr(btns = [], type = "extraBtns") {
    if (!btns?.length) return "";
    if (!["extraBtns", "operateBtns"].includes(type)) throw new Error(`操作按钮类型有误：${type}`);
    let str = `:${type}="[`;
    str += btns.map(btn => `'${btn}'`).join(", ");
    str += `]"`;
    return `${str}${N}    @${type}="on${upperFirst(type)}"${N}`;
  },
  /**
   * 获取根元素的属性字符串
   * @param {object} attrs 根元素的属性
   * @returns {string}
   */
  getAttrsStr(attrs = {}) {
    const keys = Object.keys(attrs);
    let str = "";
    keys.forEach(key => {
      str += ``;
    });
    return str;
  },
};
